<!-- 选项-component -->
<template>
  <li
    @click="handleClick"
    class="flex items-center justify-between lg:py-3.5 py-4 px-5 group cursor-pointer hover:text-theme-color hover:bg-light-background dark:hover:bg-4x-dark-foreground"
  >
    <div class="flex items-center">
      <div class="mr-4">
        <i :class="`pi pi-${curType}`" />
      </div>
      <b class="group-hover-text-theme text-sm font-bold">{{
        i18nStore.translate(curContent)
      }}</b>
    </div>
    <div class="ml-2" v-if="curIcon.type">
      <i
        class="vue-feather group-hover-text-theme opacity-50 feather feather-arrow-down"
        :class="`pi pi-${curIcon.type}`"
        style="font-size: 12px"
      />
    </div>
  </li>
  <!-- toast -->
  <Toast position="right" group="formEditToast" />
  <Dialog
    v-model:visible="visible"
    modal
    :header="i18nStore.translate('your_directory_name')"
    :style="{ width: '25rem' }"
  >
    <div class="flex align-items-center gap-3 mb-3">
      <label for="username" class="font-semibold w-6rem">{{
        i18nStore.translate('please_enter_a_file_name')
      }}</label>
      <InputText
        id="username"
        class="flex-auto"
        autocomplete="off"
        v-model="filesname"
      />
    </div>
    <div class="flex justify-content-end gap-2">
      <Button
        type="button"
        :label="i18nStore.translate('confirm')"
        @click="addFiles"
      ></Button>
    </div>
  </Dialog>
</template>

<script setup>
import {
  useFlagStore,
  useI18nStore,
  useFileStore,
  useToastStore,
  useUserInfoStore,
  SORT_ORDER,
  SORT_TYPE
} from '@/stores';
import { upload } from '@/apis/upload';
import { addFolder, recoveryFolder, recoveryFile } from '@/apis/file';
import Toast from 'primevue/toast';
const flagStore = useFlagStore();
const i18nStore = useI18nStore();
const fileStore = useFileStore();
const toastStore = useToastStore();
const userInfoStore = useUserInfoStore();

const props = defineProps({
  option: {
    type: Object,
    default: () => {}
  }
});
const curType = ref('');
const curContent = ref('');
const curIcon = ref({});
const emit = defineEmits(['close']);
const visible = ref(false);
const filesname = ref('');

// 初始化
onMounted(() => {
  curType.value = props.option.type;
  curContent.value = props.option.content;
  if (props.option.icon) {
    curIcon.value = props.option.icon;
  }
});
// 获取腾讯云token
async function getTmpSecret() {
  const { data } = await http({
    url: '/tool/sts',
    method: 'GET'
  });
  const {
    tmpSecretId: TmpSecretId,
    tmpSecretKey: TmpSecretKey,
    sessionToken: SecurityToken
  } = data.credentials;
  const { startTime: StartTime, expiredTime: ExpiredTime } = data;
  return {
    authorization: {
      TmpSecretId,
      TmpSecretKey,
      SecurityToken,
      StartTime,
      ExpiredTime
    },
    requestId: data.requestId
  };
}
// 单个文件上传校验大小
const basicUpload = async (files, folderId) => {
  const { authorization, requestId } = await getTmpSecret();

  if (fileStore.Type === 2) {
    if (files[0].size <= 314572800) {
      if (files[0].size <= userInfoStore.userInfo.file_size) {
        uplode(authorization, requestId, files, folderId);
        return;
      } else {
        toastStore.showToast({
          severity: 'error',
          detail: i18nStore.translate(
            'upgrade_to_free_version_or_buy_advanced_package'
          ),
          life: 999999,
          group: 'upload_failed'
        });
        return;
      }
    } else {
      toastStore.showToast({
        severity: 'error',
        detail: i18nStore.translate(
          'small_file_upload_file_size_cannot_exceed_300M'
        ),
        life: 999999,
        group: 'upload_failed'
      });
      return;
    }
  } else if (fileStore.Type === 1) {
    if (files[0].size <= userInfoStore.userInfo.file_space_now) {
      uplode(authorization, requestId, files, folderId);
      return;
    } else {
      toastStore.showToast({
        severity: 'error',
        detail: i18nStore.translate(
          'insufficient_remaining_storage_space_please_upgrade_package_or_purchase_space'
        ),
        life: 999999,
        group: 'upload_failed'
      });
      return;
    }
  }
};
// 单个文件上传触发
const uploadFiles = (folderId) => {
  const input = document.createElement('input');
  input.type = 'file';
  input.multiple = false;
  input.onchange = (e) => {
    basicUpload(input.files, folderId);
    input.remove();
  };
  input.click();
};
// 上传文件夹并校验大小
const uploadWholeFolder = () => {
  const input = document.createElement('input');
  input.type = 'file';
  input.webkitdirectory = true;
  input.onchange = async (e) => {
    console.log(e.target.files);
    const files = Array.from(input.files);
    const folders = {};
    let totalSize = 0; // 初始化总文件大小为0
    files.forEach((file) => {
      totalSize += file.size;
      const pathParts = file.webkitRelativePath.split('/');
      pathParts.pop(); // 移除并保存文件名
      let currentPath = '';
      // 构建文件夹路径，不包括文件名
      pathParts.forEach((part, index) => {
        currentPath += (index ? '/' : '') + part;
        if (!folders[currentPath]) {
          folders[currentPath] = {
            name: part,
            parentPath: currentPath.substring(0, currentPath.lastIndexOf('/')),
            files: []
          };
        }
      });
      // 将文件添加到其对应的文件夹
      if (folders[currentPath]) {
        folders[currentPath].files.push(file);
      }
    });

    // 检查总文件大小是否超过用户剩余空间
    if (totalSize > userInfoStore.userInfo.file_space_now) {
      toastStore.showToast({
        severity: 'error',
        detail: i18nStore.translate(
          'insufficient_remaining_storage_space_please_upgrade_package_or_purchase_space'
        ),
        life: 999999,
        group: 'upload_failed'
      });
      return;
    }
    const { authorization, requestId } = await getTmpSecret();
    // 为每个路径创建文件夹，并上传其文件
    for (const folderPath in folders) {
      const folder = folders[folderPath];
      const parentFolderId =
        folders[folder.parentPath]?.folderId || fileStore.curFolderId;
      const { message: folderId } = await addFolder({
        name: folder.name,
        pid: parentFolderId,
        type: 1
      });
      folder.folderId = folderId;
      if (folder.files.length > 0) {
        uplode(authorization, requestId, folder.files, folderId);
      }
    }

    fileStore.updateFileList(fileStore.curFolderId);
  };
  input.click();
};
// 将文件数组循环上传文件夹
const uplode = async (authorization, requestId, files, folderId) => {
  for (let file of files) {
    const task = upload(authorization, requestId, file, folderId)
      .then((res) => {
        toastStore.showToast({
          severity: 'success',
          detail:
            '[' +
            res.data.name +
            ']' +
            '  ' +
            i18nStore.translate('upload_success'),
          life: 2000,
          group: 'upload_success'
        });
        setTimeout(() => {
          toastStore.closeToastGroup('upload_success');
        }, 3000);
        if (fileStore.curFolderId === folderId) {
          fileStore.updateFileList(fileStore.curFolderId);
        }
      })
      .catch((err) => {
        toastStore.showToast({
          severity: 'error',
          detail:
            '[' + err.name + ']' + '  ' + i18nStore.translate('upload_failed'),
          life: 999999,
          group: 'upload_failed'
        });
      });
    fileStore.addUploadTask(task);
  }
};

const addFiles = () => {
  if (!filesname.value) return;
  addFolder({
    name: filesname.value,
    pid: fileStore.curFolderId,
    type: 1
  }).then(() => {
    emit('close');
    fileStore.updateFileList(fileStore.curFolderId);
  });
  visible.value = false;
  filesname.value = '';
};
// 选项类型配置
const typeConfig = {
  // 列表视图
  list: 'list',
  // 网格视图
  grid: 'th-large',
  // 日期排序
  date: 'calendar',
  // 名称排序
  name: 'language',
  // 删除
  delete: 'trash',
  // 上传文件
  upload_file: 'upload',
  // 上传整个文件夹
  upload_folder: 'cloud-upload',
  // 新建文件夹
  add_folder: 'folder-open',
  // 分享
  share: 'link',
  // 细节
  detail: 'eye',
  // 下载
  download: 'cloud-download',
  recovery: 'map',
  // 彻底删除
  delete_forever: 'times-circle'
};

watch(
  () => [fileStore.curSortType, fileStore.curSortOrder],
  () => {
    switch (curType.value) {
      case typeConfig.date:
        if (fileStore.curSortType === SORT_TYPE.DATE) {
          if (fileStore.curSortOrder === SORT_ORDER.ASC) {
            curIcon.value = { type: 'arrow-up' };
          } else {
            curIcon.value = { type: 'arrow-down' };
          }
        } else {
          curIcon.value = {};
        }
        break;
      case typeConfig.name:
        if (fileStore.curSortType === SORT_TYPE.FILE_NAME) {
          if (fileStore.curSortOrder === SORT_ORDER.ASC) {
            curIcon.value = { type: 'arrow-up' };
          } else {
            curIcon.value = { type: 'arrow-down' };
          }
        } else {
          curIcon.value = {};
        }
        break;

      default:
        break;
    }
  }
);
const handleClick = () => {
  switch (curType.value) {
    case typeConfig.list:
      // 切换为列表视图
      fileStore.toggleGridironPlan(false);
      curType.value = typeConfig.grid;
      curContent.value = 'grid_view';
      break;
    case typeConfig.grid:
      // 切换为网格视图
      fileStore.toggleGridironPlan(true);
      curType.value = typeConfig.list;
      curContent.value = 'list_view';
      break;
    case typeConfig.date:
      // 根据日期切换排序
      if (fileStore.curSortOrder === SORT_ORDER.ASC) {
        fileStore.switchSortFunc(SORT_TYPE.DATE, SORT_ORDER.DESC);
      } else if (fileStore.curSortOrder === SORT_ORDER.DESC) {
        fileStore.switchSortFunc(SORT_TYPE.DATE, SORT_ORDER.ASC);
      } else {
        fileStore.switchSortFunc(SORT_TYPE.DATE, SORT_ORDER.ASC);
      }
      break;
    case typeConfig.name:
      // 根据名称切换排序
      if (fileStore.curSortOrder === SORT_ORDER.ASC) {
        fileStore.switchSortFunc(SORT_TYPE.FILE_NAME, SORT_ORDER.DESC);
      } else if (fileStore.curSortOrder === SORT_ORDER.DESC) {
        fileStore.switchSortFunc(SORT_TYPE.FILE_NAME, SORT_ORDER.ASC);
      } else {
        fileStore.switchSortFunc(SORT_TYPE.FILE_NAME, SORT_ORDER.ASC);
      }
      break;
    case typeConfig.delete:
      // 删除文件或文件夹
      if (props.option.file) {
        fileStore.deleteFile(props.option.file, 1).then(() => {
          curType.value = typeConfig.delete;
          emit('close');
        });
        curType.value = 'spin pi-spinner';
      }
      break;
    case typeConfig.upload_file:
      // 上传文件
      uploadFiles(fileStore.curFolderId);
      emit('close');
      break;
    case typeConfig.add_folder:
      // 新建文件夹
      visible.value = true;
      break;
    case typeConfig.upload_folder:
      // 上传整个文件夹
      uploadWholeFolder();
      emit('close');
      break;
    case typeConfig.share:
      // 分享
      flagStore.setShareBoardOpen(true);
      emit('close');
      break;
    case typeConfig.detail:
      // 查看详情
      emit('close');
      nextTick(() => {
        flagStore.setInfoBoardOpen(true);
      });
      break;
    case typeConfig.download:
      fileStore.downloadFile(fileStore.curFileInfo).then((res) => {
        if (res) {
          curType.value = typeConfig.download;
        } else {
          toastStore.showToast({
            severity: 'error',
            summary: i18nStore.translate(
              'insufficient_remaining_storage_space_please_upgrade_package_or_purchase_space'
            ),
            detail: '',
            life: 2000,
            group: 'upload_success'
          });
        }
        emit('close');
      });
      curType.value = 'spin pi-spinner';

      break;
    case typeConfig.recovery:
      if (props.option.file.type == 'folder') {
        recoveryFolder({ folder_id: props.option.file.folder_id }).then(
          (res) => {
            if (res.status == 0) {
              toastStore.showToast({
                severity: 'success',
                summary: i18nStore.translate('recovery_success'),
                detail: '',
                life: 2000,
                group: 'upload_success'
              });
              fileStore.getdelFileList(0, 'trash');
              emit('close');
            }
          }
        );
      } else {
        recoveryFile({ file_id: props.option.file.file_id }).then((res) => {
          if (res.status == 0) {
            toastStore.showToast({
              severity: 'success',
              summary: i18nStore.translate('recovery_success'),
              life: 2000,
              group: 'upload_success'
            });
            fileStore.getdelFileList(0, 'trash');
            emit('close');
          }
        });
      }
      break;
    case typeConfig.delete_forever:
      fileStore.deleteFile(props.option.file, 2).then(() => {
        curType.value = typeConfig.delete;
        emit('close');
      });
      curType.value = 'spin pi-spinner';
      break;
    default:
      break;
  }
};
</script>

<style scoped lang="scss">
@import './index.scss';
</style>
